package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dyun.tool.mybatis.domain.BaseEntity;
import com.dyun.tool.mybatis.domain.PageDomain;
import com.dyun.tool.ssecurity.utils.YunSecurityUtils;
import com.ruoyi.project.setting.security.utils.UserUtils;
import com.ruoyi.project.setting.utils.DataScopeUtils;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.support.DateRange;
import com.ruoyi.project.system.entity.SysDept;
import com.ruoyi.project.system.entity.SysUser;
import com.ruoyi.project.system.entity.SysUserRole;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserRoleService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.system.vo.SysUserRoleVO;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.validation.CreateGroup;
import net.dreamlu.mica.core.validation.UpdateGroup;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 控制层
 *
 * @author dy
 */
@RestController
@RequestMapping("/system/user")
@AllArgsConstructor
public class SysUserController extends BaseController {

    private final ISysUserService sysUserService;

    private final ISysUserRoleService sysUserRoleService;

    private final ISysDeptService sysDeptService;

    /**
     * 分页
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public R<IPage<SysUser>> list(SysUser sysUser, PageDomain pageDomain, DateRange dateRange) {
        // 根据父ID查询所有子ID
        List<SysDept> sysDepts = new ArrayList<>();
        if ($.isNotNull(sysUser.getCreateDept())) {
            sysDepts = sysDeptService.list(new LambdaQueryWrapper<SysDept>()
                    .eq(SysDept::getId, sysUser.getCreateDept())
                    .or()
                    .apply(CommonConstants.SQL_FIND_IN_SET, sysUser.getCreateDept()));
        }
        IPage<SysUser> pages = sysUserService.page(startPage(pageDomain), new LambdaQueryWrapper<SysUser>()
                .like($.isNotBlank(sysUser.getUserName()), SysUser::getUserName, sysUser.getUserName())
                .eq($.isNotNull(sysUser.getStatus()), SysUser::getStatus, sysUser.getStatus())
                .like($.isNotBlank(sysUser.getPhone()), SysUser::getPhone, sysUser.getPhone())
                .in($.isNotEmpty(sysDepts), SysUser::getCreateDept, sysDepts.stream().map(BaseEntity::getId).collect(Collectors.toList()))
                .between($.isAnyNotBlank(dateRange.getBeginTime(), dateRange.getEndTime()), SysUser::getCreateTime, dateRange.getBeginTime(), dateRange.getEndTime())
                .apply(DataScopeUtils.getDataScopeSql("sys_user"), 1));
        return success(pages);
    }

    /**
     * 详情
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/detail")
    public R<SysUser> detail(Long id) {
        SysUser sysUser = sysUserService.getById(id);
        SysUserRoleVO userRoleVO = $.copy(sysUser, SysUserRoleVO.class);
        List<SysUserRole> userRoleList = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, id));
        userRoleVO.setRoleIds(userRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
        return success(userRoleVO);
    }

    /**
     * 新增
     */
    @SysLog(title = "用户管理", businessType = BusinessTypeEnum.INSERT)
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping("/add")
    public R add(@Validated(value = {CreateGroup.class}) @RequestBody SysUserRoleVO sysUserRoleVO) {
        SysUser userCheck = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq($.isNotBlank(sysUserRoleVO.getUserName()), SysUser::getUserName, sysUserRoleVO.getUserName())
                .eq($.isNotBlank(sysUserRoleVO.getPhone()), SysUser::getPhone, sysUserRoleVO.getPhone())
                .eq($.isNotBlank(sysUserRoleVO.getEmail()), SysUser::getEmail, sysUserRoleVO.getEmail()));
        if ($.isNotNull(userCheck)) {
            if (userCheck.getUserName().equals(sysUserRoleVO.getUserName())) {
                return fail("新增用户'" + sysUserRoleVO.getUserName() + "'失败，登录账号已存在");
            }
            if (userCheck.getPhone().equals(sysUserRoleVO.getPhone())) {
                return fail("新增用户'" + sysUserRoleVO.getUserName() + "'失败，手机号码已存在");
            }
            if (userCheck.getEmail().equals(sysUserRoleVO.getEmail())) {
                return fail("新增用户'" + sysUserRoleVO.getUserName() + "'失败，邮箱账号已存在");
            }
        }
        sysUserRoleVO.setSocialCode(UserConstants.BACKEND);
        SysDept sysDept = sysDeptService.getById(sysUserRoleVO.getCreateDept());
        sysUserRoleVO.setTenantId(UserUtils.turnIntoTenantId(sysUserRoleVO.getCreateDept(), sysDept.getAncestors()));
        sysUserRoleVO.setPassword(YunSecurityUtils.getPasswordEncoder().encode(sysUserRoleVO.getPassword()));
        return status(sysUserService.addUserRole(sysUserRoleVO));
    }

    /**
     * 修改
     */
    @SysLog(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/update")
    public R update(@Validated(value = {UpdateGroup.class}) @RequestBody SysUserRoleVO sysUserRoleVO) {
        if (UserUtils.isAdmin(sysUserRoleVO.getId())) {
            return fail("不允许操作超级管理员用户");
        }
        SysUser userCheck = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq($.isNotBlank(sysUserRoleVO.getUserName()), SysUser::getUserName, sysUserRoleVO.getUserName())
                .eq($.isNotBlank(sysUserRoleVO.getPhone()), SysUser::getPhone, sysUserRoleVO.getPhone())
                .eq($.isNotBlank(sysUserRoleVO.getEmail()), SysUser::getEmail, sysUserRoleVO.getEmail()));
        if ($.isNotNull(userCheck)) {
            if (userCheck.getUserName().equals(sysUserRoleVO.getUserName()) && !userCheck.getId().equals(sysUserRoleVO.getId())) {
                return fail("新增用户'" + sysUserRoleVO.getUserName() + "'失败，登录账号已存在");
            }
            if (userCheck.getPhone().equals(sysUserRoleVO.getPhone()) && !userCheck.getId().equals(sysUserRoleVO.getId())) {
                return fail("新增用户'" + sysUserRoleVO.getUserName() + "'失败，手机号码已存在");
            }
            if (userCheck.getEmail().equals(sysUserRoleVO.getEmail()) && !userCheck.getId().equals(sysUserRoleVO.getId())) {
                return fail("新增用户'" + sysUserRoleVO.getUserName() + "'失败，邮箱账号已存在");
            }
        }
        SysDept sysDept = sysDeptService.getById(sysUserRoleVO.getCreateDept());
        sysUserRoleVO.setTenantId(UserUtils.turnIntoTenantId(sysUserRoleVO.getCreateDept(), sysDept.getAncestors()));
        return status(sysUserService.updateUserRole(sysUserRoleVO));
    }

    /**
     * 修改用户信息
     */
    @SysLog(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/partialupdate")
    public R partialupdate(@RequestBody SysUser sysUser) {
        if (UserUtils.isAdmin(sysUser.getId())) {
            return fail("不允许操作超级管理员用户");
        }
        SysUser updateUser = new SysUser();
        updateUser.setId(sysUser.getId());
        updateUser.setStatus(sysUser.getStatus());
        String password = sysUser.getPassword();
        if ($.isNotBlank(password)) {
            updateUser.setPassword(YunSecurityUtils.getPasswordEncoder().encode(password));
        }
        return status(sysUserService.updateById(updateUser));
    }

    /**
     * 删除
     */
    @SysLog(title = "用户管理", businessType = BusinessTypeEnum.DELETE)
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @DeleteMapping("/delete/{ids}")
    @SneakyThrows
    public R delete(@PathVariable Long[] ids) {
        List<SysUser> sysUsers = new ArrayList<>();
        List<Long> idList = new ArrayList<>(Arrays.asList(ids));
        idList.forEach(v -> {
            if (v.equals(1L)) {
                throw new CustomException("不允许操作超级管理员用户");
            }
            SysUser sysUser = new SysUser();
            sysUser.setId(v);
            sysUsers.add(sysUser);
        });
        boolean result = sysUserService.updateBatchById(sysUsers) && sysUserService.removeByIds(idList);
        return status(result);
    }
}
